<template>
  <div class="aricle-list">
    <van-pull-refresh
    v-model="isLoading"
    @refresh="onRefresh"
    :success-text="refreshText"
    success-duration="900"
    >
      <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      :error.sync="error"
      error-text="请求失败，点击重新加载"
      @load="onLoad"
    >
      <ArticleItem v-for="(article,index) in list" :key="index" :article="article"></ArticleItem>
      <!-- <van-cell v-for="(article,index) in list" :key="index" :title="article.title" /> -->
    </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
// 获取文章列表
import { getArticle } from '@/api/article'
// 导入文章列表项
import ArticleItem from '@/components/article-item'
export default {
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      timestamp: null, // 请求获取下一页数据的时间戳
      error: false, // 请求失败提示
      isLoading: false, // 控制是否可以进行下拉刷新 false可以 true禁止
      refreshText: '' // 下拉刷新提示文本
    }
  },
  props: {
    channels: {
      requires: true
    }
  },
  methods: {
    // 获取文章列表
    async onLoad () {
      try {
        const { data } = await getArticle({
          channel_id: this.channels.id,
          timestamp: Date.now() // 获取最新数据 每次亲求传送最新时间戳
        })
        const { results } = data.data
        this.list.push(...results)
        // 3加载结束后将loading设置为false
        this.loading = false
        // 4判断数据是否全部加载完成
        if (results.length) {
          // 获取下一页时间的时间戳
          this.timestamp = data.data.pre_timestamp
        } else {
          // 数据已将全部加载完毕
          this.finished = true
        }
      } catch (err) {
        this.error = true // 开启错误提示
        this.loading = false // 结束loading的加载
      }
    },
    // 下拉刷新
    async onRefresh () {
      try {
        const { data } = await getArticle({
          channel_id: this.channels.id,
          timestamp: this.timestamp || Date.now()
        })
        const { results } = data.data
        this.list.unshift(...results)
        // 3加载结束后将loading设置为false
        this.isLoading = false
        this.refreshText = '刷新成功'
      } catch (err) {
        // 刷新失败
        this.isLoading = false
        this.refreshText = '刷新失败'
      }
    }
  },
  components: {
    ArticleItem
  }
}
</script>

<style lang="less" scpoed>
.aricle-list {
  height: calc(100vh - 274px);
  overflow-y: auto;
}
</style>
